package com.leonyr.smartipaddemo.crop;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.leonyr.lib.utils.FileUtil;
import com.leonyr.lib.utils.LogUtil;
import com.leonyr.lib.utils.StringUtil;
import com.leonyr.lib.utils.ToastUtil;
import com.leonyr.mvvm.act.Common;
import com.leonyr.mvvm.frag.AbBindFragment;
import com.leonyr.mvvm.util.RxSchedulers;
import com.leonyr.smartipaddemo.NewCommon;
import com.leonyr.smartipaddemo.R;
import com.leonyr.smartipaddemo.base.cro.IHomeView;
import com.leonyr.smartipaddemo.bean.PicItem;
import com.leonyr.smartipaddemo.conn.FileName;
import com.leonyr.smartipaddemo.databinding.FmCropHomeBinding;
import com.leonyr.smartipaddemo.photoview.PhotoViewActivity;
import com.leonyr.smartipaddemo.set.PDFUtils;
import com.leonyr.smartipaddemo.sign.SignHomeFragment;
import com.serenegiant.helper.BitmapHelper;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.parceler.Parcel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

import static com.leonyr.smartipaddemo.crop.CropImageFragment.EXTRA_CROPPED_FILE;

public class CropHomeFragment extends AbBindFragment<CropHomeViewHolder, FmCropHomeBinding> implements NewCommon.OnBackPressedListener, IHomeView, AdapterView.OnItemClickListener {

    private final int REQUEST_CODE_TAKE_PHOTO = 0x1200; //请求拍照
    private final int REQUEST_CODE_TAKE_PHOTO_CROP = 0x1201;  //请求裁剪
    private final int REQUEST_CODE_TAKE_SIGN = 0x1202; //请求签名
    private final int REQUEST_CODE_PIC_ROTATE = 0x0001; //请求签名

    CropImageFragment cropFragment;
    private boolean isCheckAll;
    private boolean isEdit;
    private ProgressDialog mProgressDialog;

    File photoFile;
    private Disposable disposable;

    List<String> fileList = new ArrayList<>();
    private MultiTypeAdapter typeAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.fm_crop_home;
    }

    @Override
    protected void initView(View rootView, Bundle savedInstanceState) {
        Binding().setFm(this);
        setVModel(new CropHomeViewHolder(getActivity()));
        getVModel().attachView(this);
        Binding().mediaRl.setLayoutManager(new GridLayoutManager(mCtx, 3));
        typeAdapter = new MultiTypeAdapter();
        typeAdapter.register(String.class, new CropFileAdapter());
        if (null == mProgressDialog) {
            mProgressDialog = new ProgressDialog(mCtx);
            mProgressDialog.setCancelable(false);
        }
        Binding().mediaRl.setAdapter(typeAdapter);
        typeAdapter.setItems(fileList);
        Binding().gridView.setAdapter(getVModel().getAdapter());
        Binding().gridView.setOnItemClickListener(this);
        Binding().gridView.setOnChangeListener(getVModel());
        isCheckAll = false;
        isEdit = false;
    }

    /**
     * 点击拍照按钮
     *
     * @param view
     */
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.action_photo:
            case R.id.action_again:
            case R.id.action_picture:
                startTakePhoto();
                break;
            case R.id.action_pdf:
                SignHomeFragment fragment = SignHomeFragment.newInstance();
                fragment.setTargetFragment(this, REQUEST_CODE_TAKE_SIGN);
                fragment.show(getFragmentManager(), SignHomeFragment.class.getSimpleName());

                break;
            case R.id.action_edit:
                Log.e("Tag", "编辑图片");
                Binding().actionEdit.setVisibility(View.GONE);
                Binding().actionPicture.setVisibility(View.GONE);
                Binding().actionBack.setVisibility(View.VISIBLE);
                Binding().actionCheckall.setVisibility(View.VISIBLE);
                Binding().actionDelete.setVisibility(View.VISIBLE);
                Binding().actionCompoud.setVisibility(View.VISIBLE);
                getVModel().checkAllVisible(true);
                isCheckAll = false;
                isEdit = true;
//                startActivity(new Intent(mCtx, PhotoViewActivity.class));
                break;

            case R.id.action_checkall:
                isCheckAll = !isCheckAll;
                if (isCheckAll) {
                    Binding().actionCheckall.setText("取消全选");
                } else {
                    Binding().actionCheckall.setText("全选");
                }
                getVModel().checkAllState(isCheckAll);
                break;
            case R.id.action_compoud:
                compoudFile();
                break;
            case R.id.action_delete:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("提示");
                builder.setMessage("确认删除所选图片？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        getVModel().delete();
                        dialogInterface.dismiss();
                    }
                });
                builder.show();
                break;
            case R.id.action_back:
                Binding().actionEdit.setVisibility(View.VISIBLE);
                Binding().actionPicture.setVisibility(View.VISIBLE);
                Binding().actionBack.setVisibility(View.GONE);
                Binding().actionCheckall.setVisibility(View.GONE);
                Binding().actionDelete.setVisibility(View.GONE);
                Binding().actionCompoud.setVisibility(View.GONE);
                getVModel().checkAllVisible(false);
                isEdit = false;
                break;

        }
    }

    /**
     * 调用摄像头并返回存储路径
     */
    private void startTakePhoto() {
        dispose();
        disposable = new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (granted) {
//                            SettingFragment.BrightControl(true);
                            photoFile = new File(getContext().getExternalFilesDir("cache"), FileName.getPhotoJpgName());
                            /*Intent startCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri uri = UriUtil.getUri(mCtx, photoFile);
                            startCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startCameraIntent.putExtra("autofocus", true); // 自动对焦
                            startCameraIntent.putExtra("showActionIcons", false);
                            if (startCameraIntent.resolveActivity(getContext().getPackageManager()) != null) {
                                startActivityForResult(startCameraIntent, REQUEST_CODE_TAKE_PHOTO);
                            }*/

                            Intent startCameraIntent = new Intent(mCtx, MineCameraActivity.class);
                            startCameraIntent.putExtra(MineCameraActivity.OUTPUT, photoFile.getPath());
                            startCameraIntent.putExtra(MineCameraActivity.CAMERA_TYPE, MineCameraActivity.TYPE_PHOTO);
                            if (startCameraIntent.resolveActivity(getContext().getPackageManager()) != null) {
                                startActivityForResult(startCameraIntent, REQUEST_CODE_TAKE_PHOTO);
                            }
                        } else {
                            ToastUtil.showToast(getContext(), "权限不足");
                        }
                    }
                });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0x0066) {
            startTakePhoto();
            return;
        }
        if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
//            SettingFragment.BrightControl(false);
        }
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_PIC_ROTATE:
                int rotation = data.getIntExtra("value", -1);
                int position = data.getIntExtra("pos", -1);
                if (position != -1 && rotation != -1) {

                    Configuration config = getResources().getConfiguration();
                    if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        getVModel().setRotateBit(position, rotation);
                    }
                }
                break;
            case REQUEST_CODE_TAKE_PHOTO:
                ArrayList<String> paths = data.getStringArrayListExtra(CameraActivity.OUTPUT);
                cropFragment = CropImageFragment.newInstance(paths);
                cropFragment.setTargetFragment(this, REQUEST_CODE_TAKE_PHOTO_CROP);
//                CropImageFragment.cropFile = path;
                openFragment(cropFragment, CropImageFragment.class.getSimpleName());
                break;
            case REQUEST_CODE_TAKE_PHOTO_CROP:
                ArrayList<String> cropPath = data.getStringArrayListExtra(EXTRA_CROPPED_FILE);

                Log.e("Size", "size +++++++==========  " + cropPath.size());
                Observable
                        .fromCallable(new Callable<List<PicItem>>() {
                            @Override
                            public List<PicItem> call() throws Exception {
                                List<PicItem> list = new ArrayList<>();
                                for (String path : cropPath) {
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inJustDecodeBounds = true;
                                    BitmapFactory.decodeFile(path, options);
                                    options.inJustDecodeBounds = false;
                                    Bitmap selectedBitmap = BitmapFactory.decodeFile(path, options);
//                                    FileUtil.deleteFile(path);
                                    list.add(new PicItem(path, selectedBitmap, false, false));
                                }
                                return list;
                            }
                        }).compose(RxSchedulers.IOMain())
                        .subscribe(new Observer<List<PicItem>>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(List<PicItem> itemList) {
                                if (itemList.size() == 0) {
                                    Toast.makeText(mCtx, "未发现图片信息", Toast.LENGTH_SHORT).show();
                                } else {
                                    getVModel().reflesh(itemList);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });


//                fileList.add(cropPath);
//                typeAdapter.notifyDataSetChanged();

//                Binding().actionPdf.setEnabled(fileList.size() > 0);

                /*photoFile = new File(cropPath);
                Glide.with(mCtx).load(photoFile).into(Binding().actionPhotoThumb);
                refreshScanFile(mCtx, cropPath);*/
                break;

            case REQUEST_CODE_TAKE_SIGN:
                try {
                    String signPath = data.getStringExtra(SignHomeFragment.RESULT_PATH_SIGN);
                    if (StringUtil.isNotBlank(signPath)) {
                        List compoudPaths = getVModel().getCompoudPaths();
                        if (compoudPaths.size() <= 0) {
                            return;
                        }
                        if (compoudPaths.size() == 1) {//直接合成签名
                            ToastUtil.showToast(mCtx, "签名成功，开始合成");
                            mProgressDialog.show();
                            mergeBitmap(compoudPaths, signPath, 3);
                        }
                        if (compoudPaths.size() >= 2) {//左右或者上下合成
                            CompoudChooseFragment ccffragment = new CompoudChooseFragment();
                            ccffragment.setListener(new CompoudChooseFragment.OnCompoudChooseListener() {
                                @Override
                                public void onLeftRight() {
                                    ToastUtil.showToast(mCtx, "签名成功，开始合成");
                                    mProgressDialog.show();
                                    mergeBitmap(compoudPaths, signPath, 1);
                                }

                                @Override
                                public void onUpDown() {
                                    ToastUtil.showToast(mCtx, "签名成功，开始合成");
                                    mProgressDialog.show();
                                    mergeBitmap(compoudPaths, signPath, 2);
                                }
                            });
                            ccffragment.show(getFragmentManager(), null);
                        }




                    /*try {
                        char[] PASSWORD = "123456".toCharArray();
                        //将证书文件放入指定路径，并读取keystore ，获得私钥和证书链
                        String pkPath = mCtx.getExternalFilesDir("file") + File.separator + "pdf.p12";
                        KeyStore ks = KeyStore.getInstance("PKCS12");
                        ks.load(new FileInputStream(pkPath), PASSWORD);
                        String alias = ks.aliases().nextElement();
                        PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
                        Certificate[] chain = ks.getCertificateChain(alias);

                        //封装签章信息
                        SignatureInfo info = new SignatureInfo();
                        info.setReason("理由");
                        info.setLocation("位置");
                        info.setPk(pk);
                        info.setChain(chain);
                        info.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
                        info.setDigestAlgorithm(DigestAlgorithms.SHA1);
                        info.setFieldName("client1");
                        info.setImagePath(signPath);
                        info.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);

                        PDFUtils.sign(pdfFile.getPath(), FileName.getPdfName(), info);
                    }catch (Exception e){
                        e.printStackTrace();
                    }*/
                    }
                } catch (Exception e) {
                    ToastUtil.showToast(mCtx, e.getMessage());
                }
                break;
        }

//        Binding().actionPhoto.setText(fileList.size() > 0 ? "下一张" : "拍照");
    }

    private void savePdf(List<String> compoudPaths, String signPath) {
        try {

            String lastPicPath = (String) compoudPaths.get(compoudPaths.size() - 1);
            Bitmap src = BitmapFactory.decodeStream(new FileInputStream(lastPicPath));
            Bitmap mark = BitmapFactory.decodeStream(new FileInputStream(signPath));
            Bitmap result = PDFUtils.mergeBitmap(src, mark);
            File rf = new File(mCtx.getExternalFilesDir("cache"), FileName.getPhotoJpgName());
            if (rf.exists()) {
                rf.delete();
            }
            FileOutputStream outputStream = new FileOutputStream(rf);
            result.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
            outputStream.flush();
            outputStream.close();
            fileList.remove(fileList.size() - 1);
            fileList.add(rf.getPath());
            src.recycle();
            mark.recycle();
            result.recycle();
            ToastUtil.showToast(mCtx, "合成完，开始存储");
            File temp = new File(lastPicPath);
            if (temp.exists()) {
                temp.delete();
            }
            temp = new File(signPath);
            if (temp.exists()) {
                temp.delete();
            }

            File pdfFile = new File(getContext().getExternalCacheDir(), FileName.getPdfName());
            if (fileList.size() <= 0) {
                ToastUtil.showToast(mCtx, "暂无图片");
                return;
            }
            PDFUtils.createPdf(pdfFile.getPath(), fileList);
            MediaViewModel.picPath.setValue(pdfFile.getPath());

            ToastUtil.showToast(mCtx, "合成Success");
//                        ToastUtil.showToast(mCtx, "合成Success\n" + pdfFile.getPath());
            FileName.createOverFile(mCtx);
            fileList.clear();
//                        typeAdapter.notifyDataSetChanged();
//                        Binding().actionPhoto.setText("拍照");
//                        Binding().actionPdf.setEnabled(false);
            getActivity().finish();
        } catch (Exception e) {
            ToastUtil.showToast(mCtx, e.getMessage());
        }
    }

    private void compoudFile() {
        List<String> paths = getVModel().getCompoudPaths();
        if (paths.size() == 0) {
            ToastUtil.showToast(mCtx, "请选择合成文件");
            return;
        }
        sign(paths);
//        if(paths.size()>=2){
//            CompoudChooseFragment ccffragment = new CompoudChooseFragment();
//            ccffragment.setListener(new CompoudChooseFragment.OnCompoudChooseListener() {
//                @Override
//                public void onLeftRight() {
//                    mProgressDialog.show();
//                    mergeBitmap(paths,true);
//                }
//
//                @Override
//                public void onUpDown() {
//                    mProgressDialog.show();
//                    mergeBitmap(paths,false);
//                }
//            });
//            ccffragment.show(getFragmentManager(),null);
//        }
    }

    /**
     * @param paths     要合成的图片路径
     * @param signPath  签名图片路径
     * @param mergeType 合成类型 1 左右合成 2 上下合成 3 直接覆盖
     */

    private void mergeBitmap(List<String> paths, String signPath, int mergeType) {
        Observable.fromCallable(new Callable<Bitmap>() {
            @Override
            public Bitmap call() throws Exception {
                Bitmap bitmapMerge = BitmapFactory.decodeFile(paths.get(0));
                switch (mergeType) {
                    case 1:
                        for (int i = 1; i < paths.size(); i++) {
                            Bitmap bitmapLast = BitmapFactory.decodeFile(paths.get(i));
                            bitmapMerge = BitmapHelper.mergeBitmap_LR(bitmapMerge, bitmapLast, false);
                        }
                        break;
                    case 2:
                        for (int i = 1; i < paths.size(); i++) {
                            Bitmap bitmapLast = BitmapFactory.decodeFile(paths.get(i));
                            bitmapMerge = BitmapHelper.mergeBitmap_TB(bitmapMerge, bitmapLast, false);
                        }
                        break;
                    case 3:
                        break;
                }
                Bitmap bitmapSign = BitmapFactory.decodeFile(signPath);
                Bitmap compoudBitmap = BitmapHelper.mergeBitmap(bitmapMerge, bitmapSign);
                return compoudBitmap;
            }
        }).compose(RxSchedulers.IOMain())
                .subscribe(new Consumer<Bitmap>() {
                    @Override
                    public void accept(Bitmap bitmap) throws Exception {
                        //保存到本地
                        boolean bool = BitmapHelper.saveBmpToFile(bitmap, getContext().getExternalCacheDir()
                                + File.separator + FileName.getPhotoPngName(), Bitmap.CompressFormat.PNG, 100);
                        mProgressDialog.dismiss();
                        if (bool) {
                            Toast.makeText(getActivity(), "合成成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), "合成失败", Toast.LENGTH_SHORT).show();
                        }
                        savePdf(paths, signPath);
                    }
                });

    }

    private void sign(List<String> paths) {
        fileList.clear();
        fileList.addAll(paths);

        SignHomeFragment fragment = SignHomeFragment.newInstance();
        fragment.setTargetFragment(this, REQUEST_CODE_TAKE_SIGN);
        fragment.show(getFragmentManager(), SignHomeFragment.class.getSimpleName());
    }

    private void refreshScanFile(Context c, String mPhotoFile) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.parse(mPhotoFile); //out is your output file
        mediaScanIntent.setData(contentUri);
        c.sendBroadcast(mediaScanIntent);
    }

    private void dispose() {

        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public boolean onBackPressed() {
        LogUtil.e("==============");
        if (null != fileList && fileList.size() > 0) {
            for (String f : fileList) {
                if (f != null && !f.isEmpty()) {
                    File file = new File(f);
                    if (file.exists()) {
                        FileUtil.copyFile(f, new File(mCtx.getExternalCacheDir(), file.getName()).getPath());
                        file.delete();
                    }
                }
            }
            FileName.createOverFile(mCtx);
        }
        return false;
    }

    @Override
    public void onDestroy() {
        dispose();
        super.onDestroy();
//        getVModel().dispose();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.e("OnItem", "onClick ----------------------  " + position);
        if (isEdit) {
            getVModel().setPicSelected(position);
        } else {
            Intent intent = new Intent(mCtx, PhotoViewActivity.class);
            intent.putExtra("path", getVModel().getPosPath(position));
            intent.putExtra("pos", position);
            startActivityForResult(intent, 0x0001);
//            startActivity(intent);
        }
    }

    @Parcel
    public static class CropHomeType implements Common.Type {
        @NonNull
        @Override
        public AbBindFragment newFragment() {
            return new CropHomeFragment();
        }

        @NonNull
        @Override
        public String getTag() {
            return CropHomeFragment.class.getSimpleName();
        }
    }
}
